var actbill = require('../model/order_bill')
var actcart = require('../../../xc/sys/cart')
var wsactcart = require('../../../xc/sys/purchaseorder')

import drawQrcode from '../../../utils/weapp-qrcode.js';
var actprobill = require('../../../xc/model/pro_contents')
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    folddata:{},
    // time: 30 * 60 * 60 * 1000,
    logistics:{status:-1},
    fileList: [],
    activetab: '0',
    isempty: false,
    navlist: [{
        "id": '0',
        name: "全部"
      },
      {
        "id": '-1',
        name: "待付款"
      },
      {
        "id": '1',
        name: "待发货"
      },
      {
        "id": '4',
        name: "待收货"
      },
      {
        "id": '9',
        name: "待评价"
      },
      {
        "id": '10',
        name: "已完成"
      },
      // { "id": '11', name: "退款" },
    ],
    refundnav: [{
        "id": '11',
        name: "全部"
      },
      {
        "id": '12',
        name: "退款中"
      },
      {
        "id": '13',
        name: "退款成功"
      },
      {
        "id": '14',
        name: "退款失败"
      },
    ],
    show: false,
    amountchanging:false,
    goldcoinname:"金币",
    taskname:"购买值",
  },
  overinvite(e){
    console.log(e)
  },
  folddata(e){
    var proid=e.currentTarget.dataset.proid;
    var ordernum=e.currentTarget.dataset.ordernum;
    var folddata=this.data.folddata;
    if(!folddata[ordernum]){
      folddata[ordernum]={}
    }

    folddata[ordernum][proid]=!folddata[ordernum][proid]
    this.setData({
      folddata:folddata
    })
  },
  showquest(e){
    console.log("e")
    console.log(e)
    var index=e.currentTarget.dataset.index;

    var status=!this.data.modellist[index]['queststatus']
    this.setData({
      ['modellist.['+index+']queststatus']:status
    })

  },
  set(status, ordernum) {
    this.setData({
      show: true
    })
    var code = "";
    if (status == 4) {
      code = "0021_" + ordernum;
    } else if (status == 6) {
      code = "0022_" + ordernum;
    }
    if (code) {
      drawQrcode({
        width: 200,
        height: 200,
        canvasId: 'myQrcode',
        text: code
      })
    }

  },
  onChangetabs: function (ev, isupdate) {
    if (isupdate) {
      // console.log(ev.detail.name)

      this.setData({
        activetab: ev.detail.name
      })
    } else {
      this.data.activetab = ev.detail.name
    }
    var that = this;
    that.getpagelist(that, 1, {})
  },
  xcloaddata: function (options, config) {
    console.log("config")
    console.log(config['sys_business_config'])
    var unit="￥"
    if(config.yihuo){
      if(config.yihuo.status==1){
        unit="∞"
        this.setData({
          "navlist[1].name":"待付额"
        })
      }
      this.setData({
        yihuoconfig:config.yihuo
      })
    }
    this.setData({
      unit:unit
    })
    if(config['sys_business_config']){
      this.setData({
        logistics:config['sys_business_config']['logistics']
      })
    }
    if (config.task) {
      this.setData({
        taskconfig: config.task,
        taskname: config.task.taskname,
        goldcoinname: config.task.goldcoin,
      })
    }
    var refundconfig = {
      'refundstatus': 1,
      'refundtime': 9,
    }
    var commentconfig = 1;
    if (config.order) {
      if (config.order.refundstatus) {
        refundconfig['refundstatus'] = config.order.refundstatus
      }
      if (config.order.refundtime) {
        refundconfig['refundtime'] = config.order.refundtime
      }
      // console.log("navlist")
      // console.log(config.order)

      if (config.order.comment == -1) {
        commentconfig = config.order.comment
        var arr = this.data.navlist
        arr.splice(4, 1)
        this.setData({
          navlist: arr
        })
        // console.log("navlist")
        // console.log(this.data.navlist)

        // console.log(arr)
      }
    }
    this.setData({
      refundconfig: refundconfig,
      commentconfig: commentconfig
    })

    if (config.delivery_config) {
      this.setData({
        delivconfig: config.delivery_config
      })
    }
    if (config.rebate) {
      this.setData({
        rebateconfig: config.rebate
      })
    }
    if (options.opstatus) {
      var update = {};
      if (options.opstatus > 10) {
        update['navlist'] = this.data.refundnav;
      }
      update['activetab'] = options.opstatus;
      this.setData(update)
    }

    if (config.prothem && config.prothem.themcolor) {
      var themconfig = config.prothem.themcolor.config;
      this.setData({
        themconfig: themconfig
      })
    }
    if (config.prothem && config.prothem.prolist) {
      var proconfig = config.prothem.prolist.proconfig;
      var customStyle = config.prothem.prolist.customStyle;
      var popconfig = config.prothem.popup.proconfig;
      var popCustomStyle = config.prothem.popup.customStyle;
      this.setData({
        proconfig: proconfig,
        navtype: proconfig.left.navmode,
        customStyle: customStyle,
        popconfig: popconfig,
        popCustomStyle: popCustomStyle
      })
    }

    var strwhere = {}
    // strwhere["status"] = 1
    var app = getApp();
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      if (res.status == 1) {
        that.getpagelist(that, 1, strwhere)
      }
    })
  },

  getpagelist(that, rest, strwhere) {
    that.setData({
      listloading: true
    });
    if (rest == 1) {
      if (!strwhere) {
        strwhere = {}
      }
      strwhere['auth'] = 'user';
      strwhere["status"] = this.data.activetab
      that.setData({
        modellist: []
      });
    }
    actbill.offset(that, rest, strwhere).then(function (result) {
      var updatemdoel = {listloading:false};
      if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
        if (rest == 1) {
          updatemdoel["modellist"] = result["obj"]["modellist"];
        } else {
          if (result["obj"]["modellist"].length > 0) {
            updatemdoel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
          }
        }
      }
      // that.selectComponent("#ordercomment").showmodel( updatemdoel["modellist"][0],"order")      
      wx.stopPullDownRefresh();
      that.setData(updatemdoel);
    }, function () {

    });
  },

  consignop() {
    var that = this;
    that.getpagelist(that, 1)
  },
  //申请退款后回调
  aftercommentsucess(e) {
    var that = this
    var strwhere = {}
    strwhere["status"] = this.data.activetab
    that.getpagelist(that, 1, strwhere)
  },
  //申请退款后回调
  afterapplyrefundsucess(e) {
    var that = this
    var strwhere = {}
    strwhere["status"] = this.data.activetab
    that.getpagelist(that, 1, strwhere)
  },
  changeamount(e){
    var that=this
    var aid=e.currentTarget.dataset.aid
    // console.log("this.data.taskconfig");
    // console.log(this.data.taskconfig);
    // return
    var taskconfig=this.data.taskconfig
    if(taskconfig.tipstatus==1){
      wx.showModal({
        title:taskconfig.exchangepopuptitle?taskconfig.exchangepopuptitle:'提示',
        content: taskconfig.exchangepopup?taskconfig.exchangepopup:'确认转化',
        success (res) {
          if (res.confirm) {
            that._changeamount(aid)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      that._changeamount(aid)
    }
  },
  _changeamount(aid){
    var that=this;
    this.setData({
      amountchanging:true
    })
    actbill.changeamount(aid).then(res => {
      if (res["status"] == 1) {
        that.getpagelist(that, 1)
        wx.showToast({
          title: "操作成功"
        })
      } else {
        wx.showToast({
          title: "操作失败"
        })
      }
      that.setData({
        amountchanging:false
      })
    })
  },
  optool(ev) {
    var op = ev.target.dataset.op
    var dataset = ev.currentTarget.dataset
    var item = dataset.item
  

    var that = this;
    switch (op) {
      case "wuliinfo": {
 
        if(this.data.logistics.status==1){
          wx.navigateTo({
            url: '/xc_lshop/shop/order/deliver?ordernum='+item.ordernum,
          })
        }else{
          wx.navigateToMiniProgram({
            appId: 'wx6885acbedba59c14',
            path: "pages/result/result?nu=" + item.expressnum + "&querysource=third_xcx"
          })
        }
       
        break;
      }
      case "qrcode": {
        this.set(item.status, item.ordernum)
        // console.log("fff")
        //  this.selectComponent("#qrcode").set(item.status,item.ordernum) ;
        break;
      }
      case "groupbuyagain": {

        var option = {
          aid: -1001,
          atype: -1001
        }
        var id = item.orderinfo[0]['proid']
        actprobill.showattrchose(that, id, null, 2, option)
        break;
      }
      case "buyagain": {
        if (item.ordertype == 9) {
          wx.navigateTo({
            url: '/xc_lshop/savemoney/recharge/hc/infor?gid=' + item.orderinfo.g_id + '&strtype=' + item.orderinfo.strtype
          })
        } else
        if (item.ordertype == 12) {
          wx.navigateTo({
            url: '/xc_lshop/savemoney/recharge/index?key=' + item.orderinfo.keyval,
          })
        } else if (item.ordertype == 14) {
          wx.navigateTo({
            url: '/xc_lshop/savemoney/recharge/ht/index',
          })
        } else if (item.ordertype == 16) {
          wx.navigateTo({
            url: '/xc_lshop/savemoney/recharge/yiqida/infor?id='+item.orderinfo.plateid,
          })
        }else  if (item.ordertype == 17){
          wsactcart.buyagain(item.orderinfo)
          wx.redirectTo({
            url: '/xc_lshop/wholesale/purchaseorder/index',
          })
        }else {
          actcart.buyagain(item.orderinfo)
          wx.redirectTo({
            url: '../cart/index',
          })
        }

        //cart.buyagain
        break;
      }
      case "payoldorder": {
        this.opload(true, "支付中...")
        actbill.payoldorder(item.id).then(result => {
          console.log("fffffffff")
          console.log(result)


          if (result["op"] == "paysuccess") {
            that.onChangetabs({
              detail: {
                name: "1"
              }
            }, true)
          } else if (result["op"] == "sendoder") {
            wx.showModal({
              title: "错误",
              content: result['data']['message'] ? result['data']['message'] : '系统错误',
              confirmText: "取消订单",
              cancelText: "返回首页",
              success: function (res) {
                console.log(res)
                if (res.cancel) {
                  wx.redirectTo({
                    url: '/xc_lshop/index/index',
                  })
                } else if (res.confirm) {
                  var eva = {
                    target: {
                      dataset: {
                        op: "noclosedorder"
                      }
                    },
                    currentTarget: {
                      dataset: {
                        item: item
                      }
                    }
                  }
           
                  that.optool(eva)
                }

              },
              fail: function (res) {

              }
            })

          }
          this.opload(false)
        })
        break;
      }
      case "closedorder": {
        wx.showModal({
          title: '确认关闭订单',
          content: "确认关闭订单",
          success(res) {
            if (res.confirm) {
              that.opload(true, "关闭订单中")
              actbill.closedorder(item.id).then(item => {
                if (item["status"] == 1) {
                  that.opload(false)
                  that.getpagelist(that, 1)
                  wx.showToast({
                    title: "操作成功"
                  })
                } else {
                  wx.showToast({
                    title: "操作失败"
                  })
                }
                that.opload(false)
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        break;
      }
      case "noclosedorder": {

        that.opload(true, "关闭订单中")
        actbill.closedorder(item.id).then(item => {
          if (item["status"] == 1) {
            that.opload(false)
            that.getpagelist(that, 1)
            // wx.showToast({
            //   title: ""
            // })
            wx.showModal({
              title: "操作成功",
              content: "是否返回首页",
              confirmText: "返回首页",
              cancelText: "留在此页",
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/xc_lshop/index/index',
                  })
                }

              },
              fail: function (res) {

              }
            })
          } else {
            wx.showToast({
              title: "操作失败"
            })
          }
          that.opload(false)

        })

        break;
      }
      case "finishbill": {
        var that = this;
        wx.showModal({
          title: '确认收货',
          content: "我确认，已收到货",
          success(res) {
            if (res.confirm) {
              actbill.finishbill(item.id).then(item => {
                if (item["status"] == 1) {
                  // this.setData（{
                  //   xc
                  // }
                  that.onChangetabs({
                    detail: {
                      name: "9"
                    }
                  }, true)
                  // that.opload(true)
                } else {
                  wx.showToast({
                    title: "操作失败"
                  })
                }

              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        break;
      }
      case "applyrefund": {
        var Comapplyrefund = this.selectComponent("#applyrefund");
        Comapplyrefund.showmodel(item.ordernum, 'order', item.status)
        break;
      }
      case "comment": {
        var Comordercomment = this.selectComponent("#ordercomment");
        Comordercomment.showmodel(item)
        break;
      }
      case "consignment": {
        var consignment = this.selectComponent("#consignment");
        consignment.showmodel(item)
        break;
      }
    }
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.getpagelist(that, 1)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    that.getpagelist(that, -1)
  },


})